package com.xuhuan.juc.assist;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author huan.xu
 * @Date 2021/12/29 17:12
 * @Description 信号灯：6辆车抢3个车位
 */
@Slf4j
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    log.info("{}抢到了车位", Thread.currentThread().getName());
                    TimeUnit.SECONDS.sleep(4);
                    log.info("{}离开了车位", Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, "汽车" + i).start();
        }
    }
}
